﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BBPA.Admin.SYS.Goods
{
    public partial class Form : FormPage
    {
        BLL.Goods bll = new BLL.Goods();
        Model.Goods model = new Model.Goods();
        //
        BLL.Pic bllPic = new BLL.Pic();
        BLL.Category bllCategory = new BLL.Category();
        BLL.Goods_BuyPrice_Log bllBuyPrice_Log = new BLL.Goods_BuyPrice_Log();
        BLL.Goods_SellPrice_Log bllSellPrice_Log = new BLL.Goods_SellPrice_Log();
        int CategoryID;
        protected EnumHelper.UserType userType;
        protected bool isAdmin;
        protected bool isEntry;
        protected string BuyPriceTitle = "联盟进价";
        protected void Page_Load(object sender, EventArgs e) { 
            CategoryID = DataTypePlus.requestInt(Request.QueryString["CategoryID"]);
            userType = Security.GetCurrentUserType();
            isAdmin = userType == EnumHelper.UserType.Administrator;
            isEntry = userType == EnumHelper.UserType.EntryPerson;
        }
        /// <summary>
        /// 初始化本页Model
        /// </summary>
        public override void Page_Load_DefaultModel() { model = bll.GetModel(Master.id); }
        /// <summary>
        /// 初始化表单
        /// </summary>
        public override void Form_Default()
        {
            cb_IsOffShelf.Visible = false;
            if (Master.formState == EnumHelper.FormState.add && CategoryID > 0) DDL_Category.SelectedValue = DataTypePlus.requestString(CategoryID);
            if (!isAdmin)
            {//除了管理员都 看不到：售价
                group_SellPrice.Visible = false;
                //供应商 看不到：供货商名称
                if (userType == EnumHelper.UserType.Supplier) group_Supplier.Visible = false;

                if (userType == EnumHelper.UserType.Store) BuyPriceTitle = "进价";
                else if (userType == EnumHelper.UserType.Supplier) BuyPriceTitle = "售价";
            }

            if (isEntry) group_SellPrice.Visible = true;
            //if (userType == EnumHelper.UserType.Store)
            //{//孕婴店  看不到：建议零售价
                //grouop_SuggestStorePrice.Visible = false;
            //}
            //cookie
            if (Master.formState == EnumHelper.FormState.add)
            {
                string cookie_Add_Goods_CategoryID="", cookie_Add_Goods_BrandID="", cookie_Add_Goods_SupplierID="";
                if (HttpContext.Current.Request.Cookies["Add_Goods_CategoryID"] != null) cookie_Add_Goods_CategoryID = DataTypePlus.requestString(HttpContext.Current.Request.Cookies["Add_Goods_CategoryID"].Value);
                if (HttpContext.Current.Request.Cookies["Add_Goods_BrandID"] != null) cookie_Add_Goods_BrandID = DataTypePlus.requestString(HttpContext.Current.Request.Cookies["Add_Goods_BrandID"].Value);
                if (HttpContext.Current.Request.Cookies["Add_Goods_SupplierID"] != null) cookie_Add_Goods_SupplierID = DataTypePlus.requestString(HttpContext.Current.Request.Cookies["Add_Goods_SupplierID"].Value);
                if (cookie_Add_Goods_CategoryID != "") DDL_Category.SelectedValue = cookie_Add_Goods_CategoryID;
                if (cookie_Add_Goods_BrandID != "") DDL_Brand.SelectedValue = cookie_Add_Goods_BrandID;
                if (cookie_Add_Goods_SupplierID != "") DDL_Supplier.SelectedValue = cookie_Add_Goods_SupplierID;
            }

        }
        /// <summary>
        /// 绑定表单数据【修改时用】
        /// </summary>
        public override void Form_Bind()
        {
            cb_IsOffShelf.Visible = true;
            DDL_Category.SelectedValue = DataTypePlus.requestString(model.CategoryID);
            DDL_Supplier.SelectedValue = DataTypePlus.requestString(model.SupplierID);
            DDL_Brand.SelectedValue = DataTypePlus.requestString(model.BrandID);

            dll_normtype.SelectedValue = model.Normtype;

            ddl_norm.SelectedValue = model.Norm;
            tb_normnum.Text = model.Normnum.ToString();
            tb_Name.Text = model.Name;
            tb_ShortName.Text = model.ShotrName;
            tb_Code.Text = model.Code;
            tb_Description.Text = model.Description;
            tb_BuyPrice.Text = StringPlus.showCoin(model.BuyPrice);
            tb_SellPrice.Text = StringPlus.showCoin(model.SellPrice);
            tb_SuggestStorePrice.Text = StringPlus.showCoin(model.SuggestStorePrice);
            ddl_ComeForm.SelectedValue = model.ComeFrom.ToString();

            cb_IsOffShelf.Checked = model.IsOffShelf;
            if ((isAdmin || isEntry) && model.State == (int)EnumHelper.GoodsState.WaitCheck) group_StateCheck.Visible = true;

            rp_pic.DataSource = bllPic.GetModelList("GoodsID=" + Master.id);
            rp_pic.DataBind();
        }
        /// <summary>
        /// 提交
        /// </summary>
        public override void Form_Submit()
        {
            string Name = PageValidate.SqlTextClear(DataTypePlus.requestString(tb_Name.Text));
            int DDL_CategoryID = DataTypePlus.requestInt(DDL_Category.SelectedValue);
            if (
                Master.noEmpty(Name, "[商品名称]必须填写") &&
                Master.noChongfu("Name='" + Name + "' and CategoryID=" + CategoryID, "[商品名称]重复")
                )
            {
                decimal old_BuyPrice = model.BuyPrice, old_SellPrice = model.SellPrice;//老价格
                if (model.CategoryID != DDL_CategoryID)
                {
                    //Rank
                    List<Model.Goods> listModelGoods = bll.GetModelList("CategoryID=" + DDL_CategoryID + " order by Rank desc");
                    if (listModelGoods != null && listModelGoods.Count > 0) model.Rank = listModelGoods[0].Rank + 1;
                    else model.Rank = 1;
                    //Number
                    Model.Category modelCategory = bllCategory.GetModel(DDL_CategoryID);
                    model.Number = modelCategory.Number + model.Rank.ToString().PadLeft(4, '0');//4位
                }
                model.CategoryID = DDL_CategoryID;

                if (userType == EnumHelper.UserType.Supplier) model.SupplierID = Security.GetCurrentSupplierID();
                else model.SupplierID = DataTypePlus.requestInt(DDL_Supplier.SelectedValue);
                model.BrandID = DataTypePlus.requestInt(DDL_Brand.SelectedValue);

                model.Name = Name;
                model.ShotrName = PageValidate.SqlTextClear(tb_ShortName.Text);
                model.Code = PageValidate.SqlTextClear(tb_Code.Text);
                model.Description = tb_Description.Text;
                model.ComeFrom = DataTypePlus.requestInt(ddl_ComeForm.SelectedValue);
                model.Norm = this.ddl_norm.SelectedValue;
                try
                {
                    model.Normnum = DataTypePlus.requestInt(this.tb_normnum.Text);
                }
                catch 
                {
                    model.Normnum = 1;
                }
                model.Normtype = this.dll_normtype.SelectedValue;


                model.BuyPrice = DataTypePlus.requestDecimal(tb_BuyPrice.Text);
                if (userType != EnumHelper.UserType.Buyer) model.SellPrice = DataTypePlus.requestDecimal(tb_SellPrice.Text);
                model.SuggestStorePrice = DataTypePlus.requestDecimal(tb_SuggestStorePrice.Text);

                model.IsOffShelf = cb_IsOffShelf.Checked;
                //
                if (Master.formState == EnumHelper.FormState.add)
                {

                    model.State = (isAdmin || isEntry) ? (int)EnumHelper.GoodsState.Nomal : (int)EnumHelper.GoodsState.WaitCheck;
                    Master.id = bll.Add(model);
                    //
                    HttpCookie cookie_Add_Goods_CategoryID = new HttpCookie("Add_Goods_CategoryID");
                    cookie_Add_Goods_CategoryID.Value = model.CategoryID.ToString();
                    HttpContext.Current.Response.Cookies.Add(cookie_Add_Goods_CategoryID);
                    HttpCookie cookie_Add_Goods_BrandID = new HttpCookie("Add_Goods_BrandID");
                    cookie_Add_Goods_BrandID.Value = model.BrandID.ToString();
                    HttpContext.Current.Response.Cookies.Add(cookie_Add_Goods_BrandID);
                    HttpCookie cookie_Add_Goods_SupplierID = new HttpCookie("Add_Goods_SupplierID");
                    cookie_Add_Goods_SupplierID.Value = model.SupplierID.ToString();
                    HttpContext.Current.Response.Cookies.Add(cookie_Add_Goods_SupplierID);
                }
                else
                {
                    if ((isAdmin || isEntry) && cb_StateCheck.Checked) model.State = (int)EnumHelper.GoodsState.Nomal;
                    bll.Update(model);
                }
                BLL.User_Operate_Log.Add(Security.GetCurrentUserID(), EnumHelper.TableName.Goods, Master.id, Master.formState == EnumHelper.FormState.add ? EnumHelper.OperateType.Add : EnumHelper.OperateType.Update, "商品："+model.Name);

                //价格变化
                if (model.BuyPrice != old_BuyPrice)
                {
                    Model.Goods_BuyPrice_Log modelBuyPrice_Log = new Model.Goods_BuyPrice_Log();
                    modelBuyPrice_Log.GoodsID = Master.id;
                    modelBuyPrice_Log.PriceBefore = old_BuyPrice;
                    modelBuyPrice_Log.PriceAfter = model.BuyPrice;
                    int BuyPrice_LogID_new= bllBuyPrice_Log.Add(modelBuyPrice_Log);
                    BLL.User_Operate_Log.Add(Security.GetCurrentUserID(), EnumHelper.TableName.Goods_BuyPrice_Log, BuyPrice_LogID_new,  EnumHelper.OperateType.Add , "");
                }
                if (model.SellPrice != old_SellPrice)
                {
                    Model.Goods_SellPrice_Log modelSellPrice_Log = new Model.Goods_SellPrice_Log();
                    modelSellPrice_Log.GoodsID = Master.id;
                    modelSellPrice_Log.PriceBefore = old_SellPrice;
                    modelSellPrice_Log.PriceAfter = model.BuyPrice;
                    int SellPrice_LogID_new = bllSellPrice_Log.Add(modelSellPrice_Log);
                    BLL.User_Operate_Log.Add(Security.GetCurrentUserID(), EnumHelper.TableName.Goods_SellPrice_Log, SellPrice_LogID_new, EnumHelper.OperateType.Add, "");
                }

                //图片
                string[] urlA = DataTypePlus.requestString(Request.Form["url"]).Replace(" ", "").Split(',');
                string[] picidA = DataTypePlus.requestString(Request.Form["picid"]).Replace(" ", "").Split(',');
                string[] titleA = DataTypePlus.requestString(Request.Form["title"]).Replace(" ", "").Split(',');
                //string[] iscoverA = DataTypePlus.requestString(Request.Form["iscover"]).Replace(" ", "").Split(',');
                string picIDstr = "0";
                for (int i = 0; i < urlA.Length; i++)
                {
                    if (urlA[i] != "")
                    {
                        Model.Pic modelPic = new Model.Pic();
                        int thisPicID = 0;
                        if (DataTypePlus.requestInt(picidA[i]) > 0)
                        {
                            thisPicID = DataTypePlus.requestInt(picidA[i]);
                            modelPic = bllPic.GetModel(thisPicID);
                            modelPic.Title = titleA[i];
                            bllPic.Update(modelPic);
                        }
                        else
                        {
                            modelPic.GoodsID = Master.id;
                            modelPic.URL = urlA[i];
                            modelPic.Title = titleA[i];
                            System.Drawing.Image bmp = System.Drawing.Image.FromFile(this.Server.MapPath(Server.UrlDecode(urlA[i])));
                            modelPic.Width = bmp.Width;
                            modelPic.Height = bmp.Height;
                            thisPicID = bllPic.Add(modelPic);
                            BLL.User_Operate_Log.Add(Security.GetCurrentUserID(), EnumHelper.TableName.Pic, thisPicID, EnumHelper.OperateType.Add, "");
                        }
                        if (picIDstr == "0")
                        {
                            model = bll.GetModel(Master.id);
                            model.PicID = thisPicID;
                            bll.Update(model);
                        }
                        picIDstr += "," + thisPicID;
                    }
                }
                if (picIDstr != "") foreach (Model.Pic pic in bllPic.GetModelList("GoodsID=" + Master.id + " and id not in(" + picIDstr + ")"))
                    {
                        BLL.User_Operate_Log.Add(Security.GetCurrentUserID(), EnumHelper.TableName.Pic, pic.id, EnumHelper.OperateType.Delete, "");
                        bllPic.Delete(pic.id);
                    }

                Master.SubmitOK();

            }
        }
    }
}